package com.javen.controller;

import com.javen.config.AppConfig;
import com.javen.custom.LoadBalancer;
import com.javen.entites.CommonResult;
import com.javen.entites.Order;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.net.URI;
import java.util.List;

/**
 * @author Javen
 */
@RestController
@Slf4j
public class OrderController {

//    public static final String ORDER_URL = "http://127.0.0.1:8001";
    /**
     * 使用 Eureka 实现负载均衡，需要在 AppConfig 中添加 @LoadBalanced 注解
     */
    public static final String ORDER_URL = "http://CLOUD-PROVIDER-ORDER";

    @Resource
    private RestTemplate restTemplate;

    /**
     * 服务发现，需要添加注解 @EnableDiscoveryClient
     */
    @Resource
    private DiscoveryClient discoveryClient;

    @Resource
    private LoadBalancer loadBalancer;

    /**
     * java.net.UnknownHostException: CLOUD-PROVIDER-ORDER
     * <p>
     * 出现以上异常时，需要在 {@link AppConfig} 添加注解 @LoadBalanced
     *
     * @param order 订单
     * @return {@link CommonResult}
     */
    @PostMapping(value = "/consumer/order/create")
    public CommonResult create(Order order) {
        return restTemplate.postForObject(ORDER_URL + "/order/create", order, CommonResult.class);
    }

    @GetMapping(value = "/consumer/order/get/{id}")
    public CommonResult get(@PathVariable("id") Long id) {
        ResponseEntity<CommonResult> entity = restTemplate.getForEntity(ORDER_URL + "/order/get/" + id, CommonResult.class);
        if (entity.getStatusCode().is2xxSuccessful()) {
            return entity.getBody();
        } else {
            return new CommonResult(entity.getStatusCode().value(), "操作失败");
        }
    }

    /**
     * 使用自定义实现轮询策略后需要去掉 {@link AppConfig} 上 @LoadBalanced注解，不然会出现以下异常
     * java.lang.IllegalStateException: No instances available for xxxxx
     *
     * @param id 订单号
     * @return {@link CommonResult}
     */
    @GetMapping(value = "/consumer/order/lb/get/{id}")
    public CommonResult getOrderByLb(@PathVariable("id") Long id) {
        // 通过微服务名称获取所有提供服务的实例
        List<ServiceInstance> instances = discoveryClient.getInstances("CLOUD-PROVIDER-ORDER");

        if (instances == null || instances.size() <= 0) {
            return null;
        }

        ServiceInstance serviceInstance = loadBalancer.instances(instances);
        URI uri = serviceInstance.getUri();
        log.info("请求 URI {}", uri);
        return restTemplate.getForObject(uri + "/order/get/" + id, CommonResult.class);
    }
}
